package com.wgchao.authmanager.application.service;

import com.wgchao.authmanager.application.filter.AuthMethod;
import com.wgchao.authmanager.domain.model.LoginAdminDomainService;
import com.wgchao.authmanager.domain.model.LoginAdminInfo;
import com.wgchao.authmanager.domain.params.LoginInfo;
import com.wgchao.authmanager.infrastructure.exception.TokenTypeException;
import com.wgchao.authmanager.infrastructure.token.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName: AuthorityService
 * @author: wgchao
 * @createTime: 2020/5/9 3:40 PM
 * @Description: 权限管理
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AuthorityService {
    @Autowired
    private LoginAdminDomainService loginAdminDomainService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 申请token
     * @param loginInfo
     * @return
     */
    public String accessToken(LoginInfo loginInfo, String type){
        //密码验证
        LoginAdminInfo loginAdminInfo = loginAdminDomainService.authentication(loginInfo);
        //生成token
        String accessToken = jwtUtil.createJWT(loginAdminInfo.getUname(),
                loginAdminInfo.getAgencyCode(), type);
        return accessToken;
    }

    /**
     * 检校token有效性
     * @param accessToken
     * @return
     */
    public String authenticationToken(String accessToken){
        Claims claims = jwtUtil.parseJWT(accessToken);
        if(claims.get("type").toString().equals("local")){//本地系统
            return claims.getId();
        }else{
            throw new TokenTypeException("身份令牌类型错误");
        }
    }

}
